package com.htudata.common.conf ;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = {"com.htudata.*.mapper"}, sqlSessionFactoryRef = "master2SqlSessionFactory")
public class Master2DataSourceConfig {

  @Value("${mapper.bss}")
  private String mapper_locations_bss;

  @Bean(name = {"master2DataSource"})
  @ConfigurationProperties(prefix = "spring.marster2.datasource")
  public DataSource master2DataSource() {
    return DataSourceBuilder.create().build();
  }
  
  @Bean(name = {"master2TransactionManager"})
  public DataSourceTransactionManager master2TransactionManager(@Qualifier("master2DataSource") DataSource master2DataSource) {
    return new DataSourceTransactionManager(master2DataSource);
  }
  
  @Bean(name = {"master2SqlSessionFactory"})
  public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("master2DataSource") DataSource master2DataSource) throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(master2DataSource);
    sessionFactory.setMapperLocations((new PathMatchingResourcePatternResolver())
        .getResources(mapper_locations_bss));
    return sessionFactory.getObject();
  }
}
